package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.dto.ItemDto;
import com.cskaoyan.mall.dto.ProductDetailDto;
import com.cskaoyan.mall.dto.ProductDto;
import com.cskaoyan.shopping.constants.GlobalConstants;
import com.cskaoyan.shopping.constants.ShoppingRetCode;
import com.cskaoyan.shopping.converter.ContentConverter;
import com.cskaoyan.shopping.converter.ItemConverter;
import com.cskaoyan.shopping.converter.ProductConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.entitys.ItemDesc;
import com.cskaoyan.shopping.dal.entitys.Panel;
import com.cskaoyan.shopping.dal.entitys.PanelContentItem;
import com.cskaoyan.shopping.dal.persistence.ItemDescMapper;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dal.persistence.PanelContentMapper;
import com.cskaoyan.shopping.dal.persistence.PanelMapper;
import com.cskaoyan.shopping.dto.AllProductResponse;
import com.cskaoyan.shopping.dto.PanelContentItemDto;
import com.cskaoyan.shopping.dto.PanelDto;
import com.cskaoyan.shopping.dto.ProductInfoDto;
import com.cskaoyan.shopping.form.PageRequest;
import com.cskaoyan.shopping.service.IProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class IProductServiceImpl implements IProductService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ItemDescMapper itemDescMapper;

    @Autowired
    ProductConverter productConverter;

    @Autowired
    PanelMapper panelMapper;

    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    ContentConverter contentConverter;

    @Autowired
    ItemConverter itemConverter;

    @Autowired
    RedissonClient redissonClient;



    @Override
    public ProductDetailDto getProductDetail(Long id) {
        RList<ProductDetailDto> productDetailList = redissonClient.getList(GlobalConstants.PRODUCT_ITEM_CACHE_KEY);
        productDetailList.expire(GlobalConstants.RECOMMEND_CACHE_EXPIRE, TimeUnit.DAYS); //缓存有效时间

        if(productDetailList.isEmpty()){  //若list为空,放入detail对象
            return getProductDetailDto(id, productDetailList);

        }else {  //不为空则检验list中是否已有
            for (ProductDetailDto productDetailDto : productDetailList) {  //遍历list查有没有对应id的detail已存入redis
                if (productDetailDto.getProductId().equals(id)){
                    return productDetailDto;  //有则直接返回该对象
                }
            }
            //没有就查库后插入list
            return getProductDetailDto(id, productDetailList);
        }
    }

    private ProductDetailDto getProductDetailDto(Long id, RList<ProductDetailDto> productDetailList) {
        Item item = itemMapper.selectByPrimaryKey(id);
        if (item == null) {  //商品不存在 返回状态码和信息
            throw new BizException(ShoppingRetCode.PRODUCT_NOT_EXISTS.getCode(), ShoppingRetCode.PRODUCT_NOT_EXISTS.getMessage());
        }
        ItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(id);
        // 放入list
        productDetailList.add(productConverter.toProductDetailDto(item, itemDesc));

        return productConverter.toProductDetailDto(item, itemDesc);
    }


    @Override
    public AllProductResponse getAllProduct(PageRequest pageInfo) {
        Example example = new Example(Item.class);

        String sort = pageInfo.getSort();

        // 排序规则
        if ("".equals(sort)) {  // 空时根据创建时间
            example.setOrderByClause("created desc");
        } else if (Integer.valueOf(sort) == 1) { // 1时根据价格升序
            example.setOrderByClause("price asc");
        } else if (Integer.valueOf(sort) == -1) { // -1 降序
            example.setOrderByClause("price desc");
        }

        Example.Criteria criteria = example.createCriteria();

        if (pageInfo.getPriceGt() != null) {
            criteria.andGreaterThanOrEqualTo("price", pageInfo.getPriceGt());
        }
        if (pageInfo.getPriceLte() != null) {
            criteria.andLessThanOrEqualTo("price", pageInfo.getPriceLte());
        }


        if (pageInfo.getCid() != null) {
            criteria.andEqualTo("cid", pageInfo.getCid());
        }

        PageHelper.startPage((pageInfo.getPage() - 1) * pageInfo.getSize(), pageInfo.getSize());
        List<Item> items = itemMapper.selectByExample(example);
        Long total = new PageInfo<>(items).getTotal();

        List<ProductDto> productDtos = new ArrayList<>();

        //   查询到的结果toDto
        for (Item item : items) {
            ProductDto productDto = new ProductDto();

            productDto.setProductId(item.getId());
            productDto.setSalePrice(item.getPrice());
            productDto.setProductName(item.getTitle());
            productDto.setSubTitle(item.getSell_point());
            String image = item.getImage();
            String[] images = image.split(",");
            productDto.setPicUrl(images[0]);
            productDtos.add(productDto);
        }

        AllProductResponse response = new AllProductResponse();
        response.setData(productDtos);
        response.setTotal(total);
        return  response;
    }


//    @Override
//    public List<PanelDto> getRecommendGoods() {
//        List<Panel> panels = panelMapper.selectPanelContentByPosition();
//
//        List<PanelDto> panelDtos = new ArrayList<>();
//
//        for (Panel panel : panels) {
//            PanelDto panelDto = contentConverter.panel2Dto(panel);
//
//            List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
//            List<PanelContentItemDto> panelContentItemDtos = contentConverter.panelContentItem2Dto(panelContentItems);
//            panelDto.setPanelContentItems(panelContentItemDtos);
//            panelDtos.add(panelDto);
//        }
//
//        return panelDtos;
//    }


    @Override
    public List<PanelDto> getRecommendGoods() {

        RList<PanelDto> recommendList = redissonClient.getList(GlobalConstants.RECOMMEND_PANEL_CACHE_KEY);

        if(recommendList.isEmpty()){
            List<Panel> panels = panelMapper.selectPanelContentById(GlobalConstants.RECOMMEND_PANEL_ID); //热门推荐id

            for (Panel panel : panels) {
                PanelDto panelDto = contentConverter.panel2Dto(panel);

                List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
                List<PanelContentItemDto> panelContentItemDtos = contentConverter.panelContentItem2Dto(panelContentItems);
                panelDto.setPanelContentItems(panelContentItemDtos);
                recommendList.add(panelDto);
            }
        }
        recommendList.expire(GlobalConstants.RECOMMEND_CACHE_EXPIRE, TimeUnit.DAYS); //缓存有效时间
        return recommendList;
    }

    @Override
    public List<ItemDto> getAllItems() {
        return null;
    }

    @Override
    public ProductInfoDto getItemInfo(Long productId) {
        Item item = itemMapper.selectByPrimaryKey(productId);
        ProductInfoDto productInfoDto = itemConverter.itemToProductInfoDto(item);
        return productInfoDto;
    }
}
